#!/usr/bin/env bash
# WordOps bash script to update cloudflare IP

string::isIPv4Block(){
    local -r ip="${1}"
    local stat=1

    if [[ "${ip}" =~ ^(([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\.){3}([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\/[0-9][0-9]?[0-9]?$ ]]; then
        stat=0
    fi
    return ${stat}
}

string::isIPv6Block(){
    local -r ip="${1}"
    local stat=1


    if [[ "${ip}" =~ ^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/[0-9][0-9]?[0-9]?$ ]] ; then
        stat=0
    fi
    return "${stat}"
}

set -euo pipefail
IFS=$'\n\t'
# shellcheck disable=SC2154
trap 's=$?; echo "$0: Error on line "$LINENO": $BASH_COMMAND"; tput cnorm ; exit $s' ERR

declare -r CURL_BIN=$(command -v curl)
declare -r cfIP="https://api.cloudflare.com/client/v4/ips"
declare -r cfConf='/etc/nginx/conf.d/cloudflare.conf'
declare allOK='true'
declare ips4 ips6 ip

ips4=$( ${CURL_BIN} -sL "${cfIP}" | jq -r '.result.ipv4_cidrs[]' )
ips6=$( ${CURL_BIN} -sL "${cfIP}" | jq -r '.result.ipv6_cidrs[]' )


if [ -d /etc/nginx/conf.d ]; then
    for ip in ${ips4}; do
        if ! string::isIPv4Block "${ip}"; then
            echo "Invalid IPv4 block: ${ip}" >&2
            allOK='false'
        fi
    done
    for ip in ${ips6}; do
        if ! string::isIPv6Block "${ip}"; then
            echo "Invalid IPv6 block: ${ip}" >&2
            allOK='false'
        fi
    done

    if [[ 'true' == "${allOK}" ]]; then
        echo '# WordOps (wo) set visitors real ip with Cloudflare' > "${cfConf}"

        for ip in ${ips4}; do
            echo "set_real_ip_from ${ip};" >> "${cfConf}"
        done
        for ip in ${ips6}; do
            echo "set_real_ip_from ${ip};" >> "${cfConf}"
        done

        echo 'real_ip_header CF-Connecting-IP;' >> "${cfConf}"

        nginx -t && service nginx reload
    else
        echo "There are some errors in the IP blocks" >&2
        exit 1
    fi
else
    echo "Can't find /etc/nginx/conf.d directory" >&2
    exit 1
fi
echo "Cloudflare IPs updated"
echo ""
